# To change this template, choose Tools | Templates
# and open the template in the editor.

__author__="jonathan"
__date__ ="$23-Jun-2010 19:26:17$"

from view.sprites import FixedSprite
from view.grid import Grid

READ_SIZE = 0
READ_TILES = 1
READ_CENTER = 2
READ_MAP = 3

class FileLevelCreator(object):

    def __init__(self, file_name):
        self.file_name = file_name
        self.num_tiles = 0

    def create_grid(self):

        tile_dict = {}
        vars = {
            'tile_dict': tile_dict,
        }

        # Exec the file in lockdown mode, only the above variables can be
        # accessed.
        execfile(self.file_name, {'__builtins__':None}, vars)

        self.tile_size = tuple(vars['tile_size'])
        map = str(vars['map'])
        map_center = tuple(vars['map_center'])

        # Create the grid.
        tiles = {}
        assert map != None
        for y, line in enumerate(map.split('\n')):

            if line == "":
                continue

            for x, item in enumerate(line.split(' ')):

                if item.strip() not in tile_dict:
                    raise Exception(
                        "Map uses unspecified tile type %s." % item.strip())

                image_name = tile_dict[item.strip()].get('image')
                zorder = tile_dict[item.strip()].get('zorder', 0)

                if image_name is not None:
                    tiles[(x, y)] = FixedSprite(
                        image_name,
                        self.tile_size,
                        (x * self.tile_size[0], y * self.tile_size[1], 0),
                        (x + y) * zorder
                    )
                    self.num_tiles += 1

        assert tiles != {}
        return Grid(tiles, map_center)


class SquareLevelCreator(object):

    def __init__(self, image_name, grid_size, tile_size):
        self.image_name = image_name
        self.grid_size = grid_size
        self.tile_size = tile_size
        self.num_tiles = 0

    def create_grid(self):
        tiles = {}
        for x in xrange(-self.grid_size, self.grid_size + 1):
            for y in xrange(-self.grid_size, self.grid_size + 1):
                tiles[(x, y)] = FixedSprite(
                    self.image_name,
                    self.tile_size,
                    (x * self.tile_size[0], y * self.tile_size[1], 0),
                    -1
                )
                self.num_tiles += 1

        return Grid(tiles, (0, 0))

